{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "0",
   "metadata": {},
   "source": [
    "# End of week 1 exercise\n",
    "\n",
    "To demonstrate your familiarity with OpenAI API, and also Ollama, build a tool that takes a technical question,  \n",
    "and responds with an explanation. This is a tool that you will be able to use yourself during the course!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# imports\n",
    "from IPython.display import Markdown, display, update_display\n",
    "from dotenv import load_dotenv\n",
    "import os\n",
    "import openai\n",
    "from openai import OpenAI\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# constants\n",
    "models = {\n",
    "    'MODEL_GPT': 'gpt-4o-mini',\n",
    "    'MODEL_LLAMA': 'llama3.2'\n",
    "}\n",
    "\n",
    "load_dotenv(override=True)\n",
    "api_key = os.getenv(\"OPENAI_API_KEY\")\n",
    "\n",
    "# To use ollama using openai API (ensure that ollama is running on localhost)\n",
    "ollama_via_openai = OpenAI(base_url='http://localhost:11434/v1', api_key='ollama')\n",
    "\n",
    "def model_choices(model):\n",
    "    if model in models:\n",
    "        return models[model]\n",
    "    else:\n",
    "        raise ValueError(f\"Model {model} not found in models dictionary\")\n",
    "\n",
    "def get_model_api(model='MODEL_GPT'):\n",
    "    if model == 'MODEL_GPT':\n",
    "        return openai, model_choices(model)\n",
    "    elif model == 'MODEL_LLAMA':\n",
    "        return ollama_via_openai, model_choices(model)\n",
    "    else:\n",
    "        raise ValueError(f\"Model {model} not found in models dictionary\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# set up environment\n",
    "\n",
    "system_prompt = \"\"\" You are an AI assistant helping a user find information about a product. \n",
    "The user asks you a technical question about code, and you provide a response with code snippets and explanations.\"\"\"\n",
    "\n",
    "def stream_brochure(question, model):\n",
    "    api, model_name = get_model_api(model)\n",
    "    stream = api.chat.completions.create(\n",
    "        model=model_name,\n",
    "        messages=[\n",
    "            {\"role\": \"system\", \"content\": system_prompt},\n",
    "            {\"role\": \"user\", \"content\": question}\n",
    "          ],\n",
    "        stream=True\n",
    "    )\n",
    "    \n",
    "    response = \"\"\n",
    "    display_handle = display(Markdown(\"\"), display_id=True)\n",
    "    for chunk in stream:\n",
    "        response += chunk.choices[0].delta.content or ''\n",
    "        response = response.replace(\"```\",\"\").replace(\"markdown\", \"\")\n",
    "        update_display(Markdown(response), display_id=display_handle.display_id)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Here is the question; type over this to ask something new\n",
    "\n",
    "question = \"\"\"\n",
    "Please explain what this code does and why:\n",
    "yield from {book.get(\"author\") for book in books if book.get(\"author\")}\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Get the model of your choice (choices appeared below) to answer, with streaming \n",
    "\n",
    "\"\"\"models = {\n",
    "    'MODEL_GPT': 'gpt-4o-mini',\n",
    "    'MODEL_LLAMA': 'llama3.2'\n",
    "}\"\"\"\n",
    "\n",
    "stream_brochure(question,'MODEL_GPT')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
